import React, { Component } from 'react'
import { Input, Card, Button, Radio, Form, Row, Col, message, Spin } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import { connect } from 'dva'
import { history } from 'umi'
import { getCookie } from '@/utils/cookie/cookie'
import { verifyToken } from '@/services/token'

const namespaceVeifyCode = 'verify_code'
const namespaceMaster = 'master'
const namespaceStudent = 'student'
const namespaceTeacher = 'teacher'
const namespaceWebSocket = 'websocket'
const mapStateToProps = (state) => {
    let { image } = state[namespaceVeifyCode]
    image =
        "data:image/png;base64," +
        btoa(
            new Uint8Array(image).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
            )
        );
    return {
        image
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        async getImage() {
            await dispatch({
                type: `${namespaceVeifyCode}/getImage`
            })
        },
        async checkVerifyCode(code) {
            const result = await dispatch({
                type: `${namespaceVeifyCode}/checkVerifyCode`,
                code
            })
            return result
        },
        async masterLogin(id, password) {
            const result = dispatch({
                type: `${namespaceMaster}/masterLogin`,
                id, password
            })
            return result
        },
        async studentLogin(id, password) {
            const result = dispatch({
                type: `${namespaceStudent}/studentLogin`,
                id, password
            })
            return result
        },
        async teacherLogin(id, password) {
            const result = dispatch({
                type: `${namespaceTeacher}/teacherLogin`,
                id, password
            })
            return result
        },
        async connectWS(id, onMessage, onOpen) {
            const result = dispatch({
                type: `${namespaceWebSocket}/connectWS`,
                id, onMessage, onOpen
            })
        }
    }
}
class Login extends Component {
    formRef = React.createRef()

    constructor(props) {
        super(props);
        this.state = {
            verifyCodeLoading: false,
            submitLoading: false
        }
        this.changeVerifyCode = this.changeVerifyCode.bind(this)
        this.submit = this.submit.bind(this)
    }

    componentDidMount() {
        if (window.sessionStorage.getItem("firstGotoLogin") !== "false") {
            (async () => {
                const token = getCookie('token')
                if (token) {
                    const result = await verifyToken(token)
                    if (result.status === 0 && result.code === 200 && result.data) {
                        if (!this.props.ws) {
                            this.props.connectWS(result.data.userId)
                        }
                        if (result.data.identity === 'student') {
                            history.push('/Student')
                        } else if (result.data.identity === 'teacher') {
                            history.push('/Teacher')
                        } else if (result.data.identity === 'master') {
                            history.push('/Master')
                        }
                    }
                }
            })()
        }
        this.changeVerifyCode()
    }

    async changeVerifyCode() {
        await this.props.getImage()
        this.setState({
            verifyCodeLoading: true
        })
        if (!this.props.image) {
            message.warn('刷新验证码失败，请稍后再次尝试')
        }
        this.setState({
            verifyCodeLoading: false
        })
    }

    async submit() {
        this.setState({
            submitLoading: true
        })
        this.formRef?.current?.validateFields?.()?.then(async value => {
            const { id, password, verifyCode, identity } = this.formRef.current.getFieldsValue()
            const verifyResult = await this.props.checkVerifyCode(verifyCode.toUpperCase())
            if (verifyResult.status === 0) {
                // login
                switch (identity) {
                    case 'master': {
                        const loginResult = await this.props.masterLogin(id, password)
                        if (loginResult.status === 0) {
                            this.props.connectWS(id, (message) => {
                                console.log(message)
                            }, () => {
                                console.log("onOpen")
                            })
                            // 跳转
                            history.push('/Master')
                        } else {
                            this.changeVerifyCode()
                            message.error(loginResult.message)
                        }
                        break
                    }
                    case 'student': {
                        const loginResult = await this.props.studentLogin(id, password)
                        if (loginResult.status === 0) {
                            this.props.connectWS(id, (message) => {
                                console.log(message)
                            }, () => {
                                console.log("onOpen")
                            })
                            // 跳转
                            history.push('/Student')
                        } else {
                            this.changeVerifyCode()
                            message.error(loginResult.message)
                        }
                        break
                    }
                    case 'teacher': {
                        const loginResult = await this.props.teacherLogin(id, password)
                        if (loginResult.status === 0) {
                            this.props.connectWS(id, (message) => {
                                console.log(message)
                            }, () => {
                                console.log("onOpen")
                            })
                            // 跳转
                            history.push('/Teacher')
                        } else {
                            this.changeVerifyCode()
                            message.error(loginResult.message)
                        }
                        break
                    }
                    default: console.error(`身份有误：${identity}`)
                        break
                }
            } else {
                message.error(verifyResult.message)
            }
            this.setState({
                submitLoading: false
            })
        }, () => {
            this.setState({
                submitLoading: false
            })
        })
    }

    render() {
        return <div style={{ width: '100vw', height: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Card style={{ width: '400px', height: 'auto' }}>
                <div style={{ textAlign: 'center' }}>
                    <h1>登录</h1>
                </div>
                <Form style={{ textAlign: 'center' }} labelAlign='right' ref={this.formRef} name='info'>
                    <Form.Item rules={[
                        {
                            required: true,
                            message: '内容不能为空!',
                        },
                    ]}
                        name='id'
                        label="账号"
                        labelCol={{ span: 5 }}>
                        <Input placeholder='请输入账号' />
                    </Form.Item>
                    <Form.Item rules={[
                        {
                            required: true,
                            message: '内容不能为空!',
                        },
                    ]}
                        name='password'
                        label='密码'
                        labelCol={{ span: 5 }}>
                        <Input type='password' placeholder='请输入密码' />
                    </Form.Item>
                    <Form.Item rules={[
                        {
                            required: true,
                            message: '内容不能为空!',
                        },
                    ]}
                        name='verifyCode'
                        label='验证码'
                        labelCol={{ span: 5 }}>
                        <Row>
                            <Col span={16}>
                                <Input placeholder='请输入验证码' />
                            </Col>
                            <Col span={8} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Button style={{
                                    visibility: 'visible',
                                    width: '90%',
                                    height: '90%',
                                    fontSize: '6px',
                                    border: '0px',
                                    color: '#a0a0a0',
                                    backgroundImage: `url(${this.props.image})`,
                                    backgroundRepeat: 'no-repeat',
                                    backgroundSize: '100% 100%',
                                    cursor: 'pointer'
                                }}
                                    onClick={this.changeVerifyCode}
                                >
                                    <LoadingOutlined />
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item required={true} initialValue='student' name='identity' labelCol={{ span: 0 }}>
                        <Radio.Group style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Radio value='student' defaultChecked={true}>学生</Radio>
                            <Radio value='teacher'>教师</Radio>
                            <Radio value='master'>管理员</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item labelCol={{ span: 0 }}>
                        <Spin spinning={this.state.submitLoading} >
                            <Button
                                type='primary'
                                style={{ width: '100%' }}
                                shape='round'
                                size='large'
                                htmlType='submit'
                                onClick={this.submit}
                            >登录</Button>
                        </Spin>
                    </Form.Item>
                </Form>
                <a type='link' style={{ float: 'right' }} onClick={() => {
                    message.warn({
                        key: 'passwordTips',
                        content: '请联系管理员进行修改密码',
                        duration: 10,
                        onClick: () => {
                            message.destroy('passwordTips')
                        }
                    })
                }}>忘记密码？</a>
            </Card>
        </div>
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)